package com.sortlistview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.Response;
import com.bignerdranch.android.expresshelper.R;
import com.bignerdranch.android.expresshelper.Utils.CheckNet;
import com.bignerdranch.android.expresshelper.Utils.RequestUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class MainFragment extends Fragment {
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private ClearEditText mClearEditText;
	private FrameLayout mFrameLayout;
	private LinearLayout mProgress;
	private LinearLayout mWifi;
	private Button mButton;

	private String url = "http://route.showapi.com/64-20?showapi_appid=20076&showapi_sign=b697ebeae51b4525b7ea856bade2d325&maxSize=60";
	private TextView mTopText;

	/**
	 * 汉字转换成拼音的类
	 */
	private List<SortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.activity_main1,container,false);

		mTopText = (TextView)view.findViewById(R.id.top_text);
		mTopText.setText(R.string.phone);
		mFrameLayout = (FrameLayout)view.findViewById(R.id.list_frame);
		mProgress = (LinearLayout)view.findViewById(R.id.progress);
		mWifi = (LinearLayout)view.findViewById(R.id.wifi);
		mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

		whichView(view);
		mButton = (Button)view.findViewById(R.id.refresh);
		mButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				whichView(view);
			}
		});


		return view;


	}

	private void whichView(View view) {
		if (CheckNet.getNet(getContext())){

			initViews(view);
		}else {
		mClearEditText.setVisibility(View.INVISIBLE);
		mFrameLayout.setVisibility(View.INVISIBLE);
		mProgress.setVisibility(View.INVISIBLE);
		mWifi.setVisibility(View.VISIBLE);
		}
	}

	private void initViews(View view) {
		//实例化汉字转拼音类
		SourceDateList= new ArrayList<SortModel>();
		pinyinComparator = new PinyinComparator();


		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sideBar.setTextView(dialog);


		//设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				//该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if(position != -1){
					sortListView.setSelection(position);
				}

			}
		});

		sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//这里要利用adapter.getItem(position)来获取当前position所对应的对象
//				Toast.makeText(getActivity(), ((SortModel)adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
				String num = ((SortModel)adapter.getItem(position)).getNum();
				Log.e("----num>>>",num+"");//pulltorefresh的position返回值从1开始
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ num));
				startActivity(intent);


			}
		});
		//filledData是将汉字转换为拼音的方法
//		SourceDateList = filledData(new String[]{"申通","顺丰","圆通","天天","韵达","中通","安利","安能","安利","安利","安利","安利","安利","安利","安利","安利","安利","YHOO"});


			RequestUtil.executeJSONObject(getActivity(), url, new Response.Listener<JSONObject>() {
				@Override
				public void onResponse(JSONObject o) {

					try {
						mClearEditText.setVisibility(View.VISIBLE);
						mFrameLayout.setVisibility(View.VISIBLE);
						mProgress.setVisibility(View.INVISIBLE);
						mWifi.setVisibility(View.INVISIBLE);
						JSONArray array = o.getJSONObject("showapi_res_body").getJSONArray("expressList");
						for(int i = 0;i <array.length() ;i++){
							SortModel model = new SortModel();
							model.setName(array.getJSONObject(i).getString("expName"));
							model.setNum(array.getJSONObject(i).getString("phone"));
							model.setImageUrl(array.getJSONObject(i).getString("imgUrl"));
							SourceDateList.add(model);
						}


						SourceDateList = filledData(SourceDateList);
						// 根据a-z进行排序源数据
						Collections.sort(SourceDateList, pinyinComparator);
						adapter = new SortAdapter(getActivity(), SourceDateList);
						sortListView.setAdapter(adapter);

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});









		//根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				//当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}


	/**
	 * 为ListView填充数据
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData( List<SortModel> date){


		for(int i=0; i<date.size(); i++){
			SortModel sortModel =date.get(i);
			/*Log.e("---filledData->>",sortModel.getName());
			sortModel.setName(date.get(i).getName());*/
			//汉字转换成拼音
			String pinyin = CharacterParser.converCnToPY(date.get(i).getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if(sortString.matches("[A-Z]")){
				sortModel.setSortLetters(sortString.toUpperCase());
			}else{
				sortModel.setSortLetters("#");
			}


		}
		return date;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * @param filterStr
	 */
	private void filterData(String filterStr){
		List<SortModel> filterDateList = new ArrayList<SortModel>();
		
		if(TextUtils.isEmpty(filterStr)){
			filterDateList = SourceDateList;
		}else{
			filterDateList.clear();
			for(SortModel sortModel : SourceDateList){
				String name = sortModel.getName();
				name=name.toUpperCase();
				String pname=CharacterParser.converCnToPY(name).toUpperCase();
				if(name.indexOf(filterStr.toString().toUpperCase()) != -1 || pname.startsWith(filterStr.toString().toUpperCase())){
					filterDateList.add(sortModel);
				}
			}
		}
		
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}
	
}
